<?php

namespace Tiger\Component;

use AliyunMNS\Client;
use AliyunMNS\Model\SendMessageRequestItem;
use AliyunMNS\Requests\SendMessageRequest;
use AliyunMNS\Requests\CreateQueueRequest;
use AliyunMNS\Requests\ChangeMessageVisibilityRequest;
use AliyunMNS\Requests\BatchSendMessageRequest;
use AliyunMNS\Exception\MnsException;
use Tiger\Face\QueueInterFace;

class Mns implements QueueInterFace
{
    private $_conf = null;
    private $_client = null;

    public function __construct($config)
    {
        $this->_conf = $config;
    }

    public function push($queueName, $data, $delay = 0)
    {
        $this->getClient();
        $queue = $this->_client->getQueueRef($queueName);
        $request = new SendMessageRequest(json_encode($data));
        try
        {
            $res = $queue->sendMessage($request);
        }
        catch (MnsException $e)
        {
            return -1;
        }
        return true;
    }

    public function receive($queueName, $wait = 30, $visibilityTimeout = 5)
    {
        $this->getClient();
        $queue = $this->_client->getQueueRef($queueName);
        $response = $queue->receiveMessage($wait);
        if ($response->isSucceed())
        {
            $receiptHandle = $response->getReceiptHandle();
            $msg = $response->getMessageBody();
            return [$msg, $receiptHandle];
        }
        return ['', ''];
    }

    public function delete($queueName, $receiptHandle)
    {
        $this->getClient();
        $queue = $this->_client->getQueueRef($queueName);
        $queue->deleteMessage($receiptHandle);
    }

    public function changeMessageVisibility($queueName, $receiptHandle, $visibilityTimeout = 5)
    {
        $this->getClient();
        $queue = $this->_client->getQueueRef($queueName);
        $result = $queue->ChangeMessageVisibility($receiptHandle, $visibilityTimeout);
        if ($result['state'] == 'ok')
        {
            return true;
        }
        return false;
    }

    public function batchPush($queueName, array $data)
    {
        $this->getClient();
        $queue = $this->_client->getQueueRef($queueName);
        foreach ($data as $key => $d)
        {
            $data[$key] = new SendMessageRequestItem($d);
        }
        $request = new BatchSendMessageRequest($data);
        try
        {
            $res = $queue->batchSendMessage($request);
        }
        catch (MnsException $e)
        {
            return -1;
        }
        return true;
    }

    public function getClient()
    {
        if (is_null($this->_client))
        {
            $this->_client = new Client($this->_conf['EndPoint'], $this->_conf['AccessKeyID'], $this->_conf['AccessKeySecret']);
        }
        return $this->_client;
    }
}
